package cn.kgc.vue.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/7/2
 * @description jwt  工具类
 * jwt  json  web token
 * <p>
 * Header      头部
 * {
 * "alg": "HS256",
 * "typ": "JWT"
 * }
 * Payload     载荷   即尽量不要携带用户敏感信息
 * {
 * username：'super',
 * uid:1
 * }
 * Signature   签名  secret  秘钥  java2424
 * HMACSHA256(
 * base64UrlEncode(header) + "." +
 * base64UrlEncode(payload),
 * secret)
 * xxxx.yyyy.zzzz
 */
@Component
public class JWTUtil {

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expireTime}")
    private Integer expireTime;
    private HashMap<String, Object> header;

    public JWTUtil() {
        header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
    }

    //  生成token
    public String createToken(HashMap<String, Object> payload) {

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, expireTime);

        return JWT.create()
                .withHeader(header)
                .withClaim("user", payload)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
    }

    // 校验token
    public boolean verify(String token) {
        // 当前方法如果没有抛出异常 则token校验通过
        JWT.require(Algorithm.HMAC256(secret))
                .build()
                .verify(token);

        return true;
    }


    // 解析token
    public Map<String, Object> getClaims(String token) {
        return JWT.decode(token).getClaim("user").asMap();
    }

}
